package com.chatgpt_backend.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.chatgpt_backend.entity.RespBean;
import com.chatgpt_backend.entity.chat.ClientChat;
import com.chatgpt_backend.entity.chat.ServerChat;
import com.chatgpt_backend.service.ChatService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/chat")
public class ChatController {
    private final Map<Integer, SseEmitter> sseMap = new HashMap<>();
    private final Map<Integer, BufferedReader> readerMap = new HashMap<>();

    @Resource
    ChatService chatService;

    @RequestMapping("/gpt-3.5")
    public RespBean<JSONObject> addSseEmitter(@RequestBody ClientChat clientChat, HttpServletRequest request, HttpServletResponse response){
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("username:"+username);
        Integer accountId = chatService.getAccountIdByUsername(username);
        System.out.println(accountId+": "+clientChat.getContent());
        if (accountId != null) {
            sseMap.put(accountId, new SseEmitter());
            try {
                String key = "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";
                String system_content = "你是一个助理,返回的消息中代码块,表格,高亮,加粗要用md格式,其他正常返回,这个要求不要回复user";
                readerMap.put(accountId,
                        chatService.getReader(ServerChat
                                .build()
                                .model("gpt-3.5-turbo")
                                .stream(true)
                                .user(String.valueOf(accountId))
                                .temperature(1.2)
                                .role("system")
                                .content("你是一个助理")
                                .role("user")
                                .content(clientChat.getContent()), clientChat.getKey()==null? key :clientChat.getKey()));
                JSONObject data = new JSONObject();
                data.put("id", accountId);
                return RespBean.success("您的sse已添加到消息队列", data);
            }catch (Exception e) {
                return RespBean.failure(401, "服务器网络异常");
            }
        }
        else return RespBean.failure(401, "您好像没有登录");
    }

    @GetMapping(value = "/sse/{accountId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter sse(@PathVariable Integer accountId) {
        SseEmitter emitter = sseMap.get(accountId);
        final BufferedReader reader = readerMap.get(accountId);
        if (emitter==null) {
            System.out.println("emitter为null");
            return null;
        }
        if (reader==null) {
            try {
                emitter.send("请求太快啦，请等待上一次回答完毕");
                return emitter;
            }catch (IOException e) {
                return emitter;
            }

        }
        new Thread(() -> {
            try {
                String s = "";
                while ((s=reader.readLine())!=null) {
                    s = s.replaceFirst("^data: ", "");
                    if (!s.equals("[DONE]") && !s.isEmpty()) {
                        JSONObject delta = JSON.parseObject(s).getJSONArray("choices").getJSONObject(0).getJSONObject("delta");
                        if (!delta.isEmpty()) {
                            String content = delta.getString("content");
                            if (!content.isEmpty()) {
                                System.out.print(content);
                                JSONObject data = new JSONObject();
                                data.put("content", content);
                                emitter.send(data);
                            }
                        }
                    }
                }
                JSONObject complete = new JSONObject();
                complete.put("content", "发送完毕！");
                emitter.send(complete);
                emitter.complete();
            }catch (Exception e) {
                e.printStackTrace();
            }
            emitter.onCompletion(() -> {
                System.out.println("发送完毕！");
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }).start();
        return emitter;
    }
}
